package com.ruoyi.community.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.SysHouse;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.community.domain.PayHisHouse;
import com.ruoyi.community.domain.PayHistory;
import com.ruoyi.community.domain.pay.StartChargeParam;
import com.ruoyi.community.mapper.PayHisHouseMapper;
import com.ruoyi.community.mapper.PayHistoryMapper;
import com.ruoyi.system.mapper.SysHouseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.community.mapper.PayCostMapper;
import com.ruoyi.community.domain.PayCost;
import com.ruoyi.community.service.IPayCostService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 缴费设置Service业务层处理
 * 
 * @author 韩 宁
 * @date 2021-12-14
 */
@Service
public class PayCostServiceImpl implements IPayCostService 
{
    @Autowired
    private PayCostMapper payCostMapper;

    @Autowired
    private PayHistoryMapper historyMapper;

    @Autowired
    private SysHouseMapper houseMapper;

    @Autowired
    private PayHisHouseMapper hisHouseMapper;

    /**
     * 查询缴费设置
     * 
     * @param id 缴费设置ID
     * @return 缴费设置
     */
    @Override
    public PayCost selectPayCostById(Integer id)
    {
        return payCostMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询缴费设置列表
     * 
     * @param payCost 缴费设置
     * @return 缴费设置
     */
    @Override
    public List<PayCost> selectPayCostList(PayCost payCost)
    {
        return payCostMapper.selectPayCostList(payCost);
    }

    /**
     * 新增缴费设置
     * 
     * @param payCost 缴费设置
     * @return 结果
     */
    @Override
    public int insertPayCost(PayCost payCost)
    {
        return payCostMapper.insert(payCost);
    }

    /**
     * 修改缴费设置
     * 
     * @param payCost 缴费设置
     * @return 结果
     */
    @Override
    public int updatePayCost(PayCost payCost)
    {
        return payCostMapper.updatePayCost(payCost);
    }

    /**
     * 批量删除缴费设置
     * 
     * @param ids 需要删除的缴费设置ID
     * @return 结果
     */
    @Override
    public int deletePayCostByIds(Integer[] ids)
    {
        return payCostMapper.deletePayCostByIds(ids);
    }

    /**
     * 删除缴费设置信息
     * 
     * @param id 缴费设置ID
     * @return 结果
     */
    @Override
    public int deletePayCostById(String id)
    {
        return payCostMapper.deletePayCostById(id);
    }

    /**
     * 发起收费
     * 1. typeId = 1 按户收费，不用查询 house 信息
     * 2. typeId = 2 or 3 按访房屋面积 或 人口收费 要先查询 house 信息
     * 3. 其他要对接先不考虑
     * 思路
     * 1. 先修改收费项 status == 0 收费中
     * 2. 创建 pay_history
     * 3. 向 pay_his_house 中添加信息，记录该收费项要向那些人收费
     * @param param 接收 costId（收费项Id），typeId（收费项类型） 收费户的数组，
     */
    @Transactional
    @Override
    public String start(StartChargeParam param) {
        Byte typeId = param.getTypeId();
        // 1. 先修改收费项 status == 0 收费中
        PayCost payCost = new PayCost();
        payCost.setId(param.getCostId());
        payCost.setStatus((byte) 0);
        payCostMapper.updatePayCost(payCost);
        // 2. 创建 pay_history, 手动开始和结束
        PayHistory history = new PayHistory();
        history.setCostId(param.getCostId());
        // 0 收费中 1 未收费 2 已完成（定时收费已完成本年度、季度的收费）
        history.setStatus((byte) 0);
        history.setStartTime(new Date());
        history.setCommunityId(SecurityUtils.getCommunityId());
        historyMapper.insertSelective(history);
        // 3. 向 pay_his_house 中添加信息，记录该收费项要向那些人收费
        //   根据 deptIds 查出 house 数组
        List<SysHouse> houses = houseMapper.selectHouseByDeptIds(param.getDeptIds());
        // 获取 PayHisHouse 数组，主要是根据不同的付款方式获取应付账款 due
        List<PayHisHouse> hisHouses = getHisHouses(typeId,history.getId(), param.getCostId(), param.getUnitprice(),
                houses);
        // 将 hisHouses 插入数据库表中
        if (hisHouses != null) {
            hisHouseMapper.insertList(hisHouses);
            return "收费已发起";
        } else {
            return "未知收费方式";
        }
    }

    // 更改 pay_cost 和 pay_history 中的 status 的状态为 2
    @Transactional
    @Override
    public String stop(Integer costId) {
        // 更改 pay_cost 中的 status 的状态为 2
        PayCost payCost = new PayCost();
        payCost.setId(costId);
        payCost.setStatus((byte) 2);
        payCostMapper.updatePayCost(payCost);
        // 更改 pay_history 中的 status 的状态为 2, 并添加结束时间
        PayHistory history = new PayHistory();
        history.setCostId(costId);
        history.setStatus((byte) 2);
        history.setEndTime(new Date());
        historyMapper.updateByCostId(history);
        return "该收费已结束。";
    }

    private List<PayHisHouse> getHisHouses(Byte typeId,Integer hisId, Integer costId, BigDecimal unitprice,
                                           List<SysHouse> houses) {
        List<PayHisHouse> list = new ArrayList<>();
        // 循环中添加通知
        for (SysHouse house : houses) {
            // 若房间还没有卖出去则没有收款人
            if (house.getUserId() == null) continue;
            PayHisHouse hisHouse = new PayHisHouse();
            // 设置主键 hisId 和 houseId
            hisHouse.setHisId(hisId);
            hisHouse.setHouseId(house.getId());
            hisHouse.setCostId(costId);
            hisHouse.setPayFlag(false);
            if (typeId == 1) {
                //按户收费
                hisHouse.setDue(unitprice);
            } else if (typeId == 2) {
                // 房屋面积收费
                hisHouse.setDue(unitprice.multiply(new BigDecimal(house.getArea().toString())));
            } else if (typeId == 3) {
                // 按人口收费
                hisHouse.setDue(unitprice.multiply(new BigDecimal(house.getNum().toString())));
            } else {
                return null;
            }
            list.add(hisHouse);
        }
        return list;
    }
}
